﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Caviar.Infrastructure.Attributes;
using Microsoft.AspNetCore.Http;
using StackExchange.Redis;
using Caviar.SharedKernel.Common.Helpers;
using Masuit.Tools;
using Caviar.SharedKernel.Entities.IM;
using Caviar.SharedKernel.Common.Extensions;

namespace Caviar.Infrastructure.Filter
{
    public class AuthorizeFilter : ActionFilterAttribute
    {
        private readonly IDatabase _redis;
        public AuthorizeFilter(RedisHelper client)
        {
            _redis = client.GetDatabase();
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                if (controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                    .Any(a => a.GetType().Equals(typeof(AuthorizeVerifyAttribute))))
                {
                    var token = context.HttpContext.Request.Headers["Authorization"].ToString();
                    if (token.IsNullOrEmpty())
                    {
                        context.Result = new StatusCodeResult(StatusCodes.Status401Unauthorized);
                        return;
                    }

                    var value = _redis.StringGet(token);
                    if (value.IsNull)
                    {
                        context.Result = new StatusCodeResult(StatusCodes.Status419AuthenticationTimeout);
                        return;
                    }
                }
            }
        }
    }
}
